<?php

namespace Biz\service\bizAd;

use Biz\model\bizAd\AdRechargeOrder as mAdRechargeOrder;
use Biz\model\bizAd\AdWalletLog as mAdWalletLog;
use Biz\pockets\constInterface\BizAd as iBizAd;
use Biz\service\trade\Pay;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;

class AdRechargeOrder implements iBizAd
{
    /**
     * 生成订单号
     * 10023459994321
     * 3位预留+时间戳后4位+3位随机+uid后四位
     * @param $uid
     * @return string
     */
    public static function createOrderSN($uid)
    {
        $reserved = 'AD100';

        $uid_tail = substr($uid, -4);

        $rand = sprintf("%04d", mt_rand(0, 999));

        $time_tail = substr(time(), -4);

        return $reserved . $time_tail . $rand . $uid_tail;
    }

    /**
     * 获取订单支付状态
     * @param $dsn
     * @return false|mixed
     */
    public static function getOrderPayStatus($dsn)
    {
        $order = mAdRechargeOrder::getOrder($dsn);

        return $order ? $order['pay_status'] : false;
    }


    /**
     * 创建订单
     * @param $uid
     * @param $utype
     * @param $identify
     * @param $pay_platform
     * @param $price
     * @param $remark
     * @param $adminId
     * @return array|false
     */
    public static function createOrder($uid, $utype, $identify, $pay_platform, $price, $remark = '', $adminId = 0)
    {
        $order_sn = self::createOrderSN($uid);
        if (mAdRechargeOrder::createOrder($order_sn, $uid, $utype, $identify, $pay_platform, $price, $remark,
            $adminId)) {
            $expireTime = time() + 15 * 3600; //15分钟订单过期
            return [$order_sn, $expireTime];
        }

        return false;
    }

    /**
     * 支付
     * @param $uid
     * @param $order_sn
     * @param null $payStopTime
     * @return array
     */
    public static function pay($uid, $order_sn, $payStopTime = 0)
    {
        $result_order_info = mAdRechargeOrder::getOrder($order_sn);

        if (empty($result_order_info)) {
            Log::error("function:pay#error:order#uid:{$uid}#order_sn:{$order_sn}#",
                $result_order_info);

            return [false, null];
        }

        //判断订单是否是未支付状态
        if(mAdRechargeOrder::PAY_STATUS_UNPAID != $result_order_info['pay_status']){
            Log::error('订单已支付或取消',['dsn'=>$order_sn,'pay_status'=>$result_order_info['pay_status']]);
            return [false, null];
        }

        $pay_platform = $result_order_info['pay_platform'];

        $orderInfo = [
            // 订单号
            'order_no' => $order_sn,
            // 支付金额
            'pay_amount' => $result_order_info['price'],
            // 付款详情标题
            'title' => '充值',
        ];
        if (!empty($payStopTime) && !is_null($payStopTime)) {
            $orderInfo['paystop_time'] = $payStopTime;
        }

        try {
            switch ($pay_platform) {
                case mAdRechargeOrder::PAY_PLATFORM_ALI_PAY:
                    // 支付宝扫码
                    $pay_url = Pay::getPayOrderInfo($orderInfo, Pay::_PAY_WAYS_ALIPAY_QRCODE,
                        Pay::_PAY_ORDER_TYPE_AD);
                    break;
                case mAdRechargeOrder::PAY_PLATFORM_WE_CHAT:
                    // 微信扫码
                    $pay_url = Pay::getPayOrderInfo($orderInfo, Pay::_PAY_WAYS_WECHAT_BIZ_QRCODE,
                        Pay::_PAY_ORDER_TYPE_AD);
                    break;
            }
        } catch (\Exception $e) {
            Log::error("function:pay#error:Exception#支付方式:{$pay_platform}#uid:{$uid}#order_sn:{$order_sn}#pay_amount:{$result_order_info['price']}",
                ['error' => $e->getMessage(), 'args' => func_get_args()]);

            return [false, null];
        }

        if (!empty($pay_url)) {
            $qr_code_url = ImgUrl::getQrcode($pay_url);
            Log::info("function:pay#支付方式:{$pay_platform}#uid:{$uid}#order_sn:{$order_sn}#pay_amount:{$result_order_info['price']}#支付二维码:{$qr_code_url}",
                $orderInfo);

            return [$qr_code_url, $payStopTime ?? 0];
        } else {
            Log::error("function:pay#error:pay_other#支付方式:{$pay_platform}#uid:{$uid}#order_sn:{$order_sn}#pay_amount:{$result_order_info['price']}",
                $pay_platform);

            return [false, null];
        }
    }


    /**
     * 支付成功回调
     * @param $order_sn
     * @param $other_sn
     * @param $pay_platform
     * @param $amount
     * @param $pay_time
     * @return bool
     * @throws \Exception
     */
    public static function callbackPaySuccess($order_sn, $other_sn, $pay_platform, $amount, $pay_time)
    {
        Log::info('#ad-recharge#callbackPaySuccess', [$order_sn, $other_sn, $pay_platform, $amount, $pay_time]);

        $orderInfo = mAdRechargeOrder::getOrder($order_sn);

        if (!empty($orderInfo) && $orderInfo['pay_status'] == mAdRechargeOrder::PAY_STATUS_PAID) {
            return true;
        }

        if ($pay_platform == Pay::_PAY_WAYS_ALIPAY_QRCODE) {
            $pay_platform = mAdRechargeOrder::PAY_PLATFORM_ALI_PAY;
        } elseif ($pay_platform == Pay::_PAY_WAYS_WECHAT_BIZ_QRCODE) {
            $pay_platform = mAdRechargeOrder::PAY_PLATFORM_WE_CHAT;
        }

        $orderUpdate['dsn'] = $order_sn;
        $orderUpdate['other_sn'] = $other_sn;
        $orderUpdate['pay_status'] = mAdRechargeOrder::PAY_STATUS_PAID;
        $orderUpdate['pay_time'] = strtotime($pay_time);
        $orderUpdate['pay_platform'] = $pay_platform;
        $orderUpdate['amount'] = $amount;
        $orderUpdate['order_status'] = mAdRechargeOrder::ORDER_STATUS_FINISHED;

        if (!AdWallet::recharge($orderInfo['uid'], self::UTYPE_BRAND, $amount, $orderInfo['uid'], mAdWalletLog::OP_UID_TYPE_USER,
            $orderUpdate)) {
            Log::error('#AdWallet::recharge fail', [
                $orderInfo['uid'],
                $amount,
                $orderInfo['uid'],
                mAdWalletLog::OP_UID_TYPE_USER,
                $orderUpdate
            ]);
            throw new \Exception('充值业务处理失败');
        }

    }
}